﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

using SplashOn_PhoneLib;
using Microsoft.Xna.Framework.Input.Touch;
using System.ComponentModel;
using System.Windows.Media;

namespace SplashOn_Phone
{
    public partial class GamePage : PhoneApplicationPage, INotifyPropertyChanged
    {
        public static bool isFirst = true;

        public event PropertyChangedEventHandler PropertyChanged;
        ContentManager contentManager;
        GameTimer timer;
        // For rendering the XAML onto a texture
        UIElementRenderer elementRenderer;
        System.Windows.Media.Color selectedColor;
        bool manipulationDone = false;

        SplashOn_Phone_Main splashOn_Phone_Main;

        public Brush SelectedArgbBrush
        {
            get;
            set;
        }

        public GamePage()
        {
            InitializeComponent();
            this.DataContext = this;

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            splashOn_Phone_Main = new SplashOn_Phone_Main();

            this.ManipulationStarted += ManipulationStarted_splash;
            this.ManipulationCompleted += ManipulationCompleted_splash;

            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
        }        

        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if (ActualWidth > 0 && ActualHeight > 0 && elementRenderer == null)
            {
                elementRenderer = new UIElementRenderer(this, (int)640, (int)480);
            }
        }        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            StartTransitionFromColor();
            string colorSelectedStringA = "";
            string colorSelectedStringR = "";
            string colorSelectedStringG = "";
            string colorSelectedStringB = "";            
            //NavigationContext.QueryString.TryGetValue("selectedColorA", out colorSelectedStringA);
            //NavigationContext.QueryString.TryGetValue("selectedColorR", out colorSelectedStringR);
            //NavigationContext.QueryString.TryGetValue("selectedColorG", out colorSelectedStringG);
            //NavigationContext.QueryString.TryGetValue("selectedColorB", out colorSelectedStringB);
            //DebugHelper.w(colorSelectedStringA + ", " + colorSelectedStringR + ", " + colorSelectedStringG + ", " + colorSelectedStringB + ", ");

            if (NavigationContext.QueryString.TryGetValue("selectedColorA", out colorSelectedStringA) &&
                NavigationContext.QueryString.TryGetValue("selectedColorR", out colorSelectedStringR) &&
                NavigationContext.QueryString.TryGetValue("selectedColorG", out colorSelectedStringG) &&
                NavigationContext.QueryString.TryGetValue("selectedColorB", out colorSelectedStringB))
            {                
                selectedColor = new System.Windows.Media.Color();
                selectedColor.A = byte.Parse(colorSelectedStringA);
                selectedColor.R = byte.Parse(colorSelectedStringR);
                selectedColor.G = byte.Parse(colorSelectedStringG);
                selectedColor.B = byte.Parse(colorSelectedStringB);
                DebugHelper.w(" Got Color:" + selectedColor.ToString());
                SelectedArgbBrush = new SolidColorBrush(selectedColor);                
                List<PropertyChangedEventArgs> changeCache = new List<PropertyChangedEventArgs>();
                changeCache.Add(new PropertyChangedEventArgs("SelectedArgbBrush"));
                Dispatcher.BeginInvoke(delegate()
                {
                    if (PropertyChanged != null)
                    {
                        foreach (var change in changeCache)
                            PropertyChanged(this, change);
                    }
                });
                splashOn_Phone_Main.splashon_welcome.splashColor = new Microsoft.Xna.Framework.Color(
                                                                        selectedColor.R, selectedColor.G,
                                                                        selectedColor.B, selectedColor.A);
            }   
   
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            //spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            TouchPanel.EnabledGestures = GestureType.Flick | GestureType.Tap | GestureType.DoubleTap;

            splashOn_Phone_Main.Initialize(SharedGraphicsDeviceManager.Current, contentManager, viewfinderBrush, false);
            if (!isFirst)
                SplashOn_Phone_Main.int_highlight = 1;
            else
                isFirst = false;

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);       

            try
            {
                NavigationService.RemoveBackEntry();
            }
            catch (InvalidOperationException exe)
            {
                DebugHelper.w(exe.Message);
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            splashOn_Phone_Main.Dispose();

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            HandleTouchInput();
            splashOn_Phone_Main.Update(e.ElapsedTime, this.IsEnabled, false);
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            //SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            elementRenderer.Render();

            if (splashOn_Phone_Main.VideoBackground == null)
                splashOn_Phone_Main.VideoBackground = elementRenderer.Texture;

            splashOn_Phone_Main.Draw(e.ElapsedTime);
        }

        void ManipulationStarted_splash(object sender, ManipulationStartedEventArgs e)
        {
            if (splashOn_Phone_Main.wayfinding.isWayfindingViewOn)
                return;
            DebugHelper.w("ManipulationStarted_splash" + e.ManipulationOrigin.ToString());
            if (e.ManipulationOrigin.X > 0 && e.ManipulationOrigin.X < 200 && e.ManipulationOrigin.Y > 100 && e.ManipulationOrigin.Y < 300)
            {
                System.Diagnostics.Debug.WriteLine(":: Manipulation Started =" + e.ToString() + " " + System.Environment.TickCount);
                splashOn_Phone_Main.generatePowerBar(System.Environment.TickCount, "splash");
            }
            else if (e.ManipulationOrigin.X > 500 && e.ManipulationOrigin.X < 700 && e.ManipulationOrigin.Y > 100 && e.ManipulationOrigin.Y < 300)
            {
                System.Diagnostics.Debug.WriteLine(":: Manipulation Started =" + e.ToString() + " " + System.Environment.TickCount);
                splashOn_Phone_Main.generatePowerBar(System.Environment.TickCount, "shoot");
            }
        }

        void ManipulationCompleted_splash(object sender, ManipulationCompletedEventArgs e)
        {
            if (splashOn_Phone_Main.wayfinding.isWayfindingViewOn)
                return;
            DebugHelper.w("ManipulationCompleted_splash" + e.ManipulationOrigin.ToString());
            if (e.ManipulationOrigin.X > 0 && e.ManipulationOrigin.X < 200 && e.ManipulationOrigin.Y > 100 && e.ManipulationOrigin.Y < 300)
            {
                System.Diagnostics.Debug.WriteLine(":: Manipulation Completed =" + e.ToString() + " " + System.Environment.TickCount);
                double width = System.Windows.Application.Current.Host.Content.ActualWidth / 2;
                double height = System.Windows.Application.Current.Host.Content.ActualHeight / 2;

                Vector3 nearSource = new Vector3((float)height, (float)width, 0); //gesture.Position.X, gesture.Position.Y, 0);
                Vector3 farSource = new Vector3((float)height, (float)width, 1); //gesture.Position.X, gesture.Position.Y, 1);

                Microsoft.Xna.Framework.Matrix viewMatrix = splashOn_Phone_Main.getGroundMarker() * splashOn_Phone_Main.getViewMatrix(); // The secret sauce that enables you to draw something that goes from your phone to the ground marker. 

                Vector3 nearPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(nearSource,
                    splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);
                Vector3 farPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(farSource,
                    splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);


                splashOn_Phone_Main.ShootSphere(nearPoint, farPoint, new Microsoft.Xna.Framework.Color(selectedColor.R, selectedColor.G, selectedColor.B, selectedColor.A), "splash");
            }
            else if (e.ManipulationOrigin.X > 500 && e.ManipulationOrigin.X < 700 && e.ManipulationOrigin.Y > 100 && e.ManipulationOrigin.Y < 300)
            {
                System.Diagnostics.Debug.WriteLine(":: Manipulation Completed =" + e.ToString() + " " + System.Environment.TickCount);
                double width = System.Windows.Application.Current.Host.Content.ActualWidth / 2;
                double height = System.Windows.Application.Current.Host.Content.ActualHeight / 2;

                Vector3 nearSource = new Vector3((float)height, (float)width, 0); //gesture.Position.X, gesture.Position.Y, 0);
                Vector3 farSource = new Vector3((float)height, (float)width, 1); //gesture.Position.X, gesture.Position.Y, 1);

                Microsoft.Xna.Framework.Matrix viewMatrix = splashOn_Phone_Main.getGroundMarker() * splashOn_Phone_Main.getViewMatrix(); // The secret sauce that enables you to draw something that goes from your phone to the ground marker. 

                Vector3 nearPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(nearSource,
                    splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);
                Vector3 farPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(farSource,
                    splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);

                splashOn_Phone_Main.ShootSphere(nearPoint, farPoint, new Microsoft.Xna.Framework.Color(selectedColor.R, selectedColor.G, selectedColor.B, selectedColor.A), "shoot");
            }
        }

        private void HandleTouchInput()
        {
            TouchCollection touches = TouchPanel.GetState();

            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                
                switch (gesture.GestureType)
                {
                    case GestureType.DoubleTap:
                        break;

                    case GestureType.Flick:
                        System.Diagnostics.Debug.WriteLine("Flick:: gesture.Delta.X=" + gesture.Delta.X);
                        System.Diagnostics.Debug.WriteLine("Flick:: gesture.Delta.Y=" + gesture.Delta.Y);
                        if (gesture.Delta.X > 1000)     // to go LEFT
                        {
                            splashOn_Phone_Main.HighLightScreen(0);
                            NavigationService.Navigate(new Uri(string.Format("/ColorPicker.xaml"), UriKind.Relative));
                            
                            StartTransitionToColor();
                        }
                        else if (gesture.Delta.X < -1000)   // to go RIGHT
                        {
                            splashOn_Phone_Main.HighLightScreen(2);
                            NavigationService.Navigate(new Uri(string.Format("/ObjectPicker.xaml"), UriKind.Relative));                            
                        }
                        else if (gesture.Delta.Y > 1000)   // to go UP
                        {
                            splashOn_Phone_Main.HighLightScreen(3);
                            DebugHelper.w("splashOn_Phone_Main.swtichToWayfinding()");
                            splashOn_Phone_Main.swtichToWayfinding();
                        }
                        else if (gesture.Delta.Y < -1000)   // to go UP
                        {
                            splashOn_Phone_Main.HighLightScreen(1);
                            DebugHelper.w("splashOn_Phone_Main.swtichToMainScreenFromWayfinding()");
                            splashOn_Phone_Main.swtichToMainScreenFromWayfinding();
                        }
                        break;

                    case GestureType.Tap:
                        System.Diagnostics.Debug.WriteLine("Tap:: tap gesture.Delta=" + gesture.Delta.ToString());
                        System.Diagnostics.Debug.WriteLine("Tap:: tap gesture.Position=" + gesture.Position.ToString());
                        // menu navigation
                        splashOn_Phone_Main.HighLightScreen(gesture.Position);
                        bool flag = false;
                        for (int i = 0; i < 5; i++)
                        {
                            if ((gesture.Position.X >= splashOn_Phone_Main.baseRectangle.X + (i * 112) &&
                                (gesture.Position.X <= splashOn_Phone_Main.baseRectangle.X + ((i + 1) * 112))) &&
                                (gesture.Position.Y >= splashOn_Phone_Main.baseRectangle.Top) &&
                                (gesture.Position.Y <= splashOn_Phone_Main.baseRectangle.Bottom))
                            {
                                flag = true;
                                DebugHelper.w(i + "");
                                switch (i)
                                {
                                    case 0:
                                        NavigationService.Navigate(new Uri(string.Format("/ColorPicker.xaml"), UriKind.Relative));
                                        splashOn_Phone_Main.HighLightScreen(i);
                                        break;
                                    case 1:
                                        splashOn_Phone_Main.HighLightScreen(i);
                                        break;
                                    case 2:
                                        NavigationService.Navigate(new Uri(string.Format("/ObjectPicker.xaml"), UriKind.Relative));
                                        splashOn_Phone_Main.HighLightScreen(i);
                                        break;
                                    case 3:
                                        splashOn_Phone_Main.swtichToWayfinding();
                                        splashOn_Phone_Main.HighLightScreen(i);
                                        break;
                                    case 4:
                                        SplashOn_Phone_Main.int_highlight = -1;
                                        break;
                                }
                                
                                break;
                            }
                        }
                        if (flag) 
                            break;
                        // in wayfinding screen... 
                        if (splashOn_Phone_Main.wayfinding.isWayfindingViewOn)
                            splashOn_Phone_Main.touchInput_wayfinding(new Vector2(gesture.Position.X, gesture.Position.Y));                        
                  /*      double width = System.Windows.Application.Current.Host.Content.ActualWidth / 2;
                        double height = System.Windows.Application.Current.Host.Content.ActualHeight / 2;

                      //  System.Diagnostics.Debug.WriteLine(":: Width " + width);
                      //  System.Diagnostics.Debug.WriteLine(":: Height " + height);

                        Vector3 nearSource = new Vector3((float)height, (float)width, 0); //gesture.Position.X, gesture.Position.Y, 0);
                        Vector3 farSource = new Vector3((float)height, (float)width, 1); //gesture.Position.X, gesture.Position.Y, 1);

                        Microsoft.Xna.Framework.Matrix viewMatrix = splashOn_Phone_Main.getGroundMarker() * splashOn_Phone_Main.getViewMatrix(); // The secret sauce that enables you to draw something that goes from your phone to the ground marker. 

                        Vector3 nearPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(nearSource,
                            splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);
                        Vector3 farPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(farSource,
                            splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);

                        splashOn_Phone_Main.ShootSphere(nearPoint, farPoint, selectedColor);

                        if (gesture.Delta.X > 1000)
                        {
                            //NavigationService.Navigate(new Uri(string.Format("/ColorPicker.xaml"), UriKind.Relative));
                        } */
                        break;
                 /*   case GestureType.Hold:
                      System.Diagnostics.Debug.WriteLine(":: tap gesture.Delta=" + gesture.Delta.ToString());
                        System.Diagnostics.Debug.WriteLine(":: tap gesture.Position=" + gesture.Position.ToString());

                        Vector3 nearSource = new Vector3(gesture.Position.X, gesture.Position.Y, 0);
                        Vector3 farSource = new Vector3(gesture.Position.X, gesture.Position.Y, 1);

                        Microsoft.Xna.Framework.Matrix viewMatrix = splashOn_Phone_Main.getGroundMarker() * splashOn_Phone_Main.getViewMatrix(); // The secret sauce that enables you to draw something that goes from your phone to the ground marker. 

                        Vector3 nearPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(nearSource,
                            splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);
                        Vector3 farPoint = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Unproject(farSource,
                            splashOn_Phone_Main.getProjectionMatrix(), viewMatrix, Microsoft.Xna.Framework.Matrix.Identity);

                        splashOn_Phone_Main.ShootSphere(nearPoint, farPoint, selectedColor);

                        if (gesture.Delta.X > 1000)
                        {
                            //NavigationService.Navigate(new Uri(string.Format("/ColorPicker.xaml"), UriKind.Relative));
                        }  
                        System.Diagnostics.Debug.WriteLine(":: hold gesture.Delta=" + gesture.Delta.ToString());
                        System.Diagnostics.Debug.WriteLine(":: hold gesture.Position=" + gesture.Position.ToString());
                        break;*/
                        
                }
            }
        }

        private void StartTransitionFromColor()
        {
            SlideTransition slideTransition = new SlideTransition();
            slideTransition.Mode = SlideTransitionMode.SlideLeftFadeIn;

            PhoneApplicationPage phoneApplicationPage =
            (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;

            ITransition transition = slideTransition.GetTransition(phoneApplicationPage);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();
        }

        private void StartTransitionToColor()
        {
            SlideTransition slideTransition = new SlideTransition();
            slideTransition.Mode = SlideTransitionMode.SlideRightFadeOut;            

            PhoneApplicationPage phoneApplicationPage =
            (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;

            ITransition transition = slideTransition.GetTransition(phoneApplicationPage);            
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();
        }
    }
}
